<template>
  <div class="news-edit">
    <n-card>
      <template #header>
        <div class="header-actions">
          <span>{{ isEdit ? t('news.editNews') : t('news.addNews') }}</span>
          <n-button @click="handleBack">
            {{ t('common.back') }}
          </n-button>
        </div>
      </template>

      <n-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-placement="top"
        label-width="auto"
      >
        <n-grid cols="2" :x-gap="16">
          <n-grid-item>
            <n-form-item :label="t('news.title')" path="title">
              <n-input v-model:value="formData.title" />
            </n-form-item>
          </n-grid-item>
          <n-grid-item>
            <n-form-item :label="t('news.author')" path="author">
              <n-input v-model:value="formData.author" />
            </n-form-item>
          </n-grid-item>
        </n-grid>

        <n-grid cols="2" :x-gap="16">
          <n-grid-item>
            <n-form-item :label="t('news.category')" path="category">
              <n-input v-model:value="formData.category" />
            </n-form-item>
          </n-grid-item>
          <n-grid-item>
            <n-form-item :label="t('common.status')" path="status">
              <n-select v-model:value="formData.status" :options="statusOptions" />
            </n-form-item>
          </n-grid-item>
        </n-grid>

        <n-form-item :label="t('news.summary')" path="summary">
          <n-input
            v-model:value="formData.summary"
            type="textarea"
            :rows="3"
          />
        </n-form-item>

        <n-form-item :label="t('news.tags')" path="tags">
          <n-dynamic-tags v-model:value="formData.tags" />
        </n-form-item>

        <n-form-item :label="t('news.content')" path="content">
          <div class="editor-container">
            <RichEditor v-model:value="formData.content" />
          </div>
        </n-form-item>

        <n-form-item>
          <n-space>
            <n-button type="primary" @click="handleSave" :loading="loading">
              {{ t('common.save') }}
            </n-button>
            <n-button @click="handleReset">
              {{ t('common.reset') }}
            </n-button>
          </n-space>
        </n-form-item>
      </n-form>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import {
  NCard,
  NButton,
  NForm,
  NFormItem,
  NInput,
  NSelect,
  NDynamicTags,
  NGrid,
  NGridItem,
  NSpace,
  useMessage
} from 'naive-ui'
import { newsApi } from '@/api'
import RichEditor from '@/components/RichEditor.vue'

const route = useRoute()
const router = useRouter()
const { t } = useI18n({ useScope: 'global' })
const message = useMessage()

const formRef = ref()
const loading = ref(false)

const isEdit = computed(() => !!route.params.id)

const formData = reactive({
  title: '',
  author: '',
  category: '',
  status: 'draft',
  summary: '',
  content: '',
  tags: []
})

const statusOptions = computed(() => [
  { label: t('news.status.draft'), value: 'draft' },
  { label: t('news.status.pending'), value: 'pending' },
  { label: t('news.status.published'), value: 'published' }
])

const rules = {
  title: {
    required: true,
    message: '请输入新闻标题',
    trigger: 'blur'
  },
  author: {
    required: true,
    message: '请输入作者',
    trigger: 'blur'
  },
  category: {
    required: true,
    message: '请输入分类',
    trigger: 'blur'
  },
  summary: {
    required: true,
    message: '请输入新闻摘要',
    trigger: 'blur'
  },
  content: {
    required: true,
    message: '请输入新闻内容',
    trigger: 'blur'
  }
}

const loadNewsData = async () => {
  if (!isEdit.value) return
  
  try {
    const id = Number(route.params.id)
    const response = await newsApi.getById(id)
    if (response.success) {
      const news = response.data.list.find((item: any) => item.id === id)
      if (news) {
        Object.assign(formData, {
          title: news.title,
          author: news.author,
          category: news.category,
          status: news.status,
          summary: news.summary,
          content: news.content,
          tags: news.tags || []
        })
      }
    }
  } catch (error) {
    message.error('加载新闻数据失败')
  }
}

const handleSave = async () => {
  try {
    await formRef.value?.validate()
    loading.value = true
    
    if (isEdit.value) {
      const id = Number(route.params.id)
      await newsApi.update(id, formData)
      message.success('更新成功')
    } else {
      await newsApi.create(formData)
      message.success('创建成功')
    }
    
    handleBack()
  } catch (error) {
    message.error(isEdit.value ? '更新失败' : '创建失败')
  } finally {
    loading.value = false
  }
}

const handleReset = () => {
  formRef.value?.restoreValidation()
  if (isEdit.value) {
    loadNewsData()
  } else {
    Object.assign(formData, {
      title: '',
      author: '',
      category: '',
      status: 'draft',
      summary: '',
      content: '',
      tags: []
    })
  }
}

const handleBack = () => {
  router.push('/news/list')
}

onMounted(() => {
  if (isEdit.value) {
    loadNewsData()
  }
})
</script>

<style scoped>
.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.editor-container {
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}
</style>